using System;
using System.Net;
using System.Net.Quic;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace QUICRPC
{
    public class QuicServer
    {
        private Dictionary<string, QuicConnection> onlineClients = new Dictionary<string, QuicConnection>();

        public string HELO(string name) {
            return "hi " + name;
        }
        public string GetSession(string terminal_sn) {
            return "this is demo";
        }
        public async Task StartServer()
        {
            var listener = new QuicListener(new IPEndPoint(IPAddress.Any, 5000), new QuicServerOptions
            {
                ApplicationProtocols = new[] { new QuicServerAlpnOption(Encoding.ASCII.GetBytes("myapp")) },
                DefaultStreamErrorCode = 0,
                DefaultCloseErrorCode = 0
            });

            await listener.StartAsync();
            Console.WriteLine("服务器已启动，等待连接...");

            while (true)
            {
                var connection = await listener.AcceptConnectionAsync();
                Console.WriteLine("新连接已接受");

                var stream = await connection.AcceptInboundStreamAsync();
                var buffer = new byte[1024];
                var bytesRead = await stream.ReadAsync(buffer);
                var request = QuicProtocol.Message.Deserialize(buffer.Take(bytesRead).ToArray());

                if (request != null && request.Type == QuicProtocol.MessageType.RpcCall)
                {
                    // 解析 call id
                    string[] parts = request.Data.Split(':', 2);
                    string callId = parts[0];
                    string methodCall = parts[1];

                    // 处理 RPC 调用
                    string responseData = ProcessRpcCall(methodCall);

                    // 构建带 call id 的响应
                    var response = new QuicProtocol.Message { Type = QuicProtocol.MessageType.RpcResponse, Data = $"{callId}:{responseData}" };
                    var responseBytes = response.Serialize();
                    await stream.WriteAsync(responseBytes);
                }
                else if (request != null && request.Type == QuicProtocol.MessageType.FileTransferRequest)
                {
                    // 解析 call id
                    string[] parts = request.Data.Split(':', 3);
                    string callId = parts[0];
                    string fileName = parts[1];
                    long fileSize = long.Parse(parts[2]);

                    // 处理文件传输请求
                    var response = new QuicProtocol.Message { Type = QuicProtocol.MessageType.FileTransferAccept, Data = $"{callId}:Accept" };
                    var responseBytes = response.Serialize();
                    await stream.WriteAsync(responseBytes);

                    // 接收文件数据
                    // ... 现有文件接收逻辑 ...
                }

                await stream.DisposeAsync();
                await connection.DisposeAsync();
            }
        }

        private string ProcessRpcCall(string methodCall)
        {
            // 实现 RPC 调用处理逻辑
            return "RPC 响应数据";
        }
    }
}